package com.cypher.encryptionanddecryption.util;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.cypher.encryptionanddecryption.R;

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义耗时等待框工具类
 * @author: 古霸天
 * @date: 2021/4/7
 */
public class ProgressDialogUtil {
    /** 存放对话框集合 */
    private static Map<Context, AlertDialog> map = new HashMap<>();
    /** 存放提示文字视图集合 */
    private static Map<AlertDialog, TextView> dialogTextViewMap = new HashMap<>();
    /**
     * 弹出耗时对话框
     * @param context
     */
    public static void showProgressDialog(Context context) {
        showProgressDialog(context, "");
    }

    /**
     *弹出耗时对话框
     * @param context 需要弹出对话框的活动
     * @param tip 对话框提示文字
     */
    public static void showProgressDialog(Context context, String tip) {
        if (StringUtils.isEmpty(tip)) {
            tip = "加载中...";
        }
        AlertDialog mAlertDialog = map.get(context);
        if (mAlertDialog == null) {
            mAlertDialog = new AlertDialog.Builder(context, R.style.CustomProgressDialog).create();

            View loadView = LayoutInflater.from(context).inflate(R.layout.custom_progress_dialog_view, null);
            mAlertDialog.setView(loadView, 0, 0, 0, 0);
            mAlertDialog.setCanceledOnTouchOutside(false);
            TextView tvTip = loadView.findViewById(R.id.tvTip);
            dialogTextViewMap.put(mAlertDialog, tvTip);
            map.put(context, mAlertDialog);
        }
        TextView tvTip = dialogTextViewMap.get(mAlertDialog);
        tvTip.setText(tip);
        mAlertDialog.show();
    }

    /**
     * 隐藏耗时对话框
     */
    public static void dismiss(Context context) {
        AlertDialog mAlertDialog = map.get(context);
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
    }

    /**
     * 回收静态资源
     */
    public static void destroy() {
        dialogTextViewMap = null;
        map = null;
    }
}
